package com.qingyun.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingyun.common.constant.ConfigConstants;
import com.qingyun.common.constant.Constants;
import com.qingyun.common.core.domain.entity.SysUser;
import com.qingyun.common.core.mybatisplus.core.ServicePlusImpl;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.core.redis.RedisCache;
import com.qingyun.common.enums.OrderStatusEnum;
import com.qingyun.common.exception.CustomException;
import com.qingyun.common.utils.PageUtils;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokGoods;
import com.qingyun.shop.domain.TiktokOrder;
import com.qingyun.shop.domain.TiktokOrderItem;
import com.qingyun.shop.domain.bo.order.TiktokOrderBo;
import com.qingyun.shop.domain.bo.order.TiktokOrderCreateBo;
import com.qingyun.shop.domain.bo.order.TiktokOrderQueryBo;
import com.qingyun.shop.domain.vo.TiktokOrderDetailVo;
import com.qingyun.shop.domain.vo.TiktokOrderListVo;
import com.qingyun.shop.domain.vo.TiktokOrderVo;
import com.qingyun.shop.mapper.TiktokGoodsMapper;
import com.qingyun.shop.mapper.TiktokOrderItemMapper;
import com.qingyun.shop.mapper.TiktokOrderMapper;
import com.qingyun.shop.service.ITiktokOrderService;
import com.qingyun.system.service.ISysConfigService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 订单Service业务层处理
 *
 * @author qingyun
 * @date 2021-09-04
 */
@Service
@AllArgsConstructor
public class TiktokOrderServiceImpl extends ServicePlusImpl<TiktokOrderMapper, TiktokOrder, TiktokOrderVo> implements ITiktokOrderService {

	private final TiktokGoodsMapper goodsMapper;

	private final TiktokOrderItemMapper orderItemMapper;

	private final ISysConfigService configService;

	private final RedisCache redisCache;

	@Override
	public TiktokOrderDetailVo queryById(Long id) {
		return baseMapper.selectOrderDetailById(id);
	}

	@Override
	public TableDataInfo<TiktokOrderListVo> queryPageList(TiktokOrderQueryBo bo) {
		if (bo.getShopId() == null) {
			if (SecurityUtils.isProxy()) {
				bo.setShopId(SecurityUtils.getShop().getId());
				bo.setProxyId(SecurityUtils.getProxy().getId());
			}else if(SecurityUtils.isShop()){
				bo.setShopId(SecurityUtils.getShop().getId());
			}
		}

		Page<TiktokOrderListVo> result = baseMapper.selectOrderList(PageUtils.buildPage(), bo);


		return PageUtils.buildDataInfo(result);
	}

	@Override
	public List<TiktokOrderListVo> queryList(TiktokOrderQueryBo bo) {
		if (bo.getShopId() == null) {
			SysUser user = SecurityUtils.getUser();
			if (!Constants.SYS_USER.equals(user.getUserType())) {
				bo.setShopId(SecurityUtils.getShop().getId());
			}
		}
		Page<TiktokOrderListVo> result = baseMapper.selectOrderList(PageUtils.buildPage(), bo);
		return result.getRecords();
	}

	private LambdaQueryWrapper<TiktokOrder> buildQueryWrapper(TiktokOrderBo bo) {
		Map<String, Object> params = bo.getParams();
		LambdaQueryWrapper<TiktokOrder> lqw = Wrappers.lambdaQuery();
		lqw.eq(StringUtils.isNotBlank(bo.getOrderNum()), TiktokOrder::getOrderNum, bo.getOrderNum());
		lqw.eq(bo.getShopId() != null, TiktokOrder::getShopId, bo.getShopId());
		lqw.eq(bo.getUserId() != null, TiktokOrder::getUserId, bo.getUserId());
		lqw.like(StringUtils.isNotBlank(bo.getGoodsName()), TiktokOrder::getGoodsName, bo.getGoodsName());
		lqw.eq(bo.getAmount() != null, TiktokOrder::getAmount, bo.getAmount());
		lqw.eq(bo.getSource() != null, TiktokOrder::getSource, bo.getSource());
		lqw.eq(bo.getStatus() != null, TiktokOrder::getStatus, bo.getStatus());
		lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), TiktokOrder::getRemarks, bo.getRemarks());
		lqw.eq(bo.getPayTime() != null, TiktokOrder::getPayTime, bo.getPayTime());
		return lqw;
	}

	@Override
	@Transactional
	public Boolean insertByBo(TiktokOrderCreateBo bo) {
		SysUser user = SecurityUtils.getUser();
		TiktokGoods goods = goodsMapper.selectById(bo.getGoodsId());

		String orderNum = IdUtil.simpleUUID();

		// 获取系统 订单超时时间 配置
		String timeOut = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + ConfigConstants.SYS_ORDER_PAY_TIME_OFFSET);

		if (!Validator.isNumber(timeOut) || Double.parseDouble(timeOut) < 0) {
			throw new CustomException("系统配置出错，请联系平台负责人");
		}

		Date closeTime = new Date();
		closeTime.setTime(closeTime.getTime() + Long.parseLong(timeOut) * 60 * 1000);

		// 数量 x 单价
		BigDecimal amount = null;
		if (Constants.PROXY_USER.equals(user.getUserType())) {
			// 代理商价格
			amount = new BigDecimal(bo.getQuantity()).multiply(goods.getProxyPrice());
		} else if (Constants.SHOP_USER.equals(user.getUserType())) {
			// 普通商户价格
			amount = new BigDecimal(bo.getQuantity()).multiply(goods.getPrice());
		}
		// 创建订单表
		TiktokOrder order = new TiktokOrder();
		order.setOrderNum(orderNum);
		order.setGoodsName(goods.getName());
		order.setUserId(user.getUserId());
		order.setShopId(SecurityUtils.getShop().getId());
		order.setSource(bo.getSource());
		order.setRemarks(bo.getRemarks());
		order.setCreateBy(user.getUserName());
		order.setUpdateBy(user.getUserName());
		order.setCreateTime(new Date());
		order.setUpdateTime(new Date());
		order.setAmount(amount);
		order.setStatus(OrderStatusEnum.INIT.value());
		order.setCloseTime(closeTime);

		// 创建订单详情表
		TiktokOrderItem orderItem = new TiktokOrderItem();
		orderItem.setOrderNum(orderNum);
		orderItem.setAmount(amount);
		orderItem.setGoodsId(goods.getId());
		orderItem.setQuantity(bo.getQuantity());
		orderItem.setGoodsName(goods.getName());
		orderItem.setCreateTime(new Date());

		save(order);
		orderItemMapper.insert(orderItem);

		// todo 需加入订单未在规定时间内支付，订单关闭功能


		return Boolean.TRUE;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean updateByBo(TiktokOrderBo bo) {
		TiktokOrder update = BeanUtil.toBean(bo, TiktokOrder.class);
		validEntityBeforeSave(update);
		return updateById(update);
	}

	/**
	 * 保存前的数据校验
	 *
	 * @param entity 实体类数据
	 */
	private void validEntityBeforeSave(TiktokOrder entity) {
		//TODO 做一些数据校验,如唯一约束
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		if (isValid) {
			//TODO 做一些业务上的校验,判断是否需要校验
		}
		return removeByIds(ids);
	}

	@Override
	public TiktokOrderDetailVo queryByOrderNum(String orderNum) {
		return baseMapper.selectOrderDetailByOrderNum(orderNum);
	}

	/**
	 * 订单支付结果查询
	 *
	 * @param id 订单id
	 */
	@Override
	public Boolean getPayStatus(Long id) {
		return null;
	}

	@Override
	public List<TiktokOrder> selectInvalidOrder(Date date) {
		return baseMapper.selectInvalidOrder(date);
	}
}
